package com.hitqz.robot.biz.bean;

import cn.hutool.extra.spring.SpringUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.google.common.cache.Cache;
import com.hitqz.robot.api.business.entity.JobCachesEntity;
import com.hitqz.robot.api.business.entity.RobotEntity;
import com.hitqz.robot.biz.service.JobCachesService;
import com.hitqz.robot.biz.service.RobotGroupService;
import com.hitqz.robot.biz.service.RobotJobService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * @author xupkun
 * @date 2024/8/6
 */
@Component("robotJob")
@RequiredArgsConstructor
@Slf4j
public class RobotJobSchedule {

    private final RobotJobService robotJobService;

    private final JobCachesService jobCachesService;

    private final RobotGroupService robotGroupService;

    private static String lock = "robot_task_lock";


    /**
     * 执行任务
     * @param jobId robotJobEntity.id
     * @return
     */
    public String execute(String jobId) {
        // 查询
        //RobotJobEntity robotJobEntity = robotJobService.getById(jobId);
        //if (robotJobEntity != null) {
        //    RobotJobDto robotJobDto = new RobotJobDto();
        //    robotJobDto.setId(robotJobEntity.getId());
        //    //robotJobDto.set
        //    //SpringUtil.getApplicationContext().publishEvent(robotJobDto);
        //}
        return "success";
    }


    /**
     * 一直尝试启动任务
     */
    @Scheduled(fixedDelay = 3000)
    public void checkJob() {
        Cache<Integer, List<RobotEntity>> posInfoDtoCache = SpringUtil.getBean("robotDispatch");
        for (Integer groupId: posInfoDtoCache.asMap().keySet()) {
            synchronized (lock.intern()) {
                JobCachesEntity jobCachesEntityList = jobCachesService.getOne(Wrappers.<JobCachesEntity>lambdaQuery()
                        .eq(JobCachesEntity::getGroupId, groupId)
                        .orderByAsc(JobCachesEntity::getSn)
                        .last(" limit 1"));
                if (jobCachesEntityList != null) {
                    SpringUtil.getApplicationContext().publishEvent(jobCachesEntityList);
                }
            }
        }
    }


}
